import React, { useEffect, useState } from 'react';
import AppBar from '../../AppBar';
function Home() {
    const [showToast, setShowToast] = useState(true);
    const [message, setMessage] = useState("");

    useEffect(() => {
        const timer = setTimeout(() => {
            setShowToast(false);
        }, 0);
        return () => {
            clearTimeout(timer);
        }
    }, []);

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
        e.preventDefault();
        // Add your login validation logic here
        // Assume validation succeeded, call the onLogin callback function
        const username = e.currentTarget.username.value
        const age      = e.currentTarget.age.value
        const city     = e.currentTarget.city.value
        console.log(`${username} ${age} ${city}`)
        window.Main.SaveUser({username, age, city})
      };

      useEffect(() => {
        window.Main.on('saveUserResponse', (message: string) => {
            setShowToast(true);
            setMessage(message);
            const timer = setTimeout(() => {
                setShowToast(false);
            }, 1500);
            return () => {
                clearTimeout(timer);
            }
        });
      },[message]);
    return (
        <>
            <AppBar/>
            {showToast && <div className="toast toast-center toast-middle">
                <div className="alert alert-success">
                    <span>{message}</span>
                </div>
            </div>
            }
            {!showToast && 
                    <div className="container mx-auto p-4 flex justify-center">
                    <form onSubmit={handleSubmit}>
                      <div className="mb-4">
                        <label htmlFor="username" className="block mb-2">Enter your username:</label>
                        <input type="text" id="username" placeholder="" className="input w-full max-w-xs border-1 border-red-100" required />
                      </div>
                      <div className="mb-4">
                        <label htmlFor="age" className="block mb-2">Enter your age:</label>
                        <input type="text" id="age" placeholder="" className="input w-full max-w-xs border-red-100" required />
                      </div>
                      <div className="mb-4">
                        <label htmlFor="city" className="block mb-2">Enter your city:</label>
                        <input type="text" id="city" placeholder="" className="input w-full max-w-xs border-red-100" required />
                      </div>
                      <button type="submit" className="btn btn-active btn-secondary">Save</button>
                      <button type="button" className="btn btn-active btn-warning" onClick={() => window.Main.CreateUserTable()}>Create User Table</button>
                    </form>
                  </div>
            }


        </>
    );
}

export default Home;
